<template>
  <div class="test-detail">
    <div class="test-detail__header">
      <el-button 
        type="primary" 
        :icon="ArrowLeft" 
        @click="goBack"
      >
        返回
      </el-button>
      <h2 class="test-detail__title">测试详情</h2>
    </div>

    <div v-loading="loading" class="test-detail__content">
      <template v-if="localTestDetail.id">
        <!-- 测试基本信息 -->
        <el-card class="test-info-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>测试信息</span>
            </div>
          </template>
          <div class="test-info">
            <div class="info-item">
              <span class="label">单元名称：</span>
              <span class="value">{{ localTestDetail.unitName }}</span>
            </div>
            <div class="info-item">
              <span class="label">教材名称：</span>
              <span class="value">{{ localTestDetail.programName }}</span>
            </div>
            <div class="info-item">
              <span class="label">测试时间：</span>
              <span class="value">{{ localTestDetail.testTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">测试分数：</span>
              <span class="value score" :class="getScoreClass(localTestDetail.testScore)">
                {{ localTestDetail.testScore }}分
              </span>
            </div>
            <div class="info-item">
              <span class="label">测试用时：</span>
              <span class="value">{{ formatDuration(localTestDetail.testDuration) }}</span>
            </div>
            <div class="info-item">
              <span class="label">测试评语：</span>
              <span class="value">{{ localTestDetail.testComment }}</span>
            </div>
          </div>
        </el-card>

        <!-- 测试统计 -->
        <el-card class="test-stats-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>测试统计</span>
            </div>
          </template>
          <div class="test-stats">
            <div class="stat-item">
              <div class="stat-value">{{ localTestDetail.totalQuestions }}</div>
              <div class="stat-label">总题数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value correct">{{ localTestDetail.correctAnswers }}</div>
              <div class="stat-label">正确</div>
            </div>
            <div class="stat-item">
              <div class="stat-value wrong">{{ localTestDetail.wrongAnswers }}</div>
              <div class="stat-label">错误</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ getAccuracyRate() }}%</div>
              <div class="stat-label">正确率</div>
            </div>
          </div>
        </el-card>

        <!-- 错误题目类型统计 -->
        <el-card v-if="localTestDetail.errorQuestionTypes?.length" class="error-types-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>错误题目类型统计</span>
            </div>
          </template>
          <el-table :data="localTestDetail.errorQuestionTypes" style="width: 100%">
            <el-table-column prop="questionTypeName" label="题目类型" />
            <el-table-column prop="errorCount" label="错误数量" />
            <el-table-column prop="totalCount" label="总数量" />
            <el-table-column prop="errorRate" label="错误率">
              <template #default="{ row }">
                <span class="error-rate">{{ (row.errorRate * 100).toFixed(1) }}%</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 错误单词列表 -->
        <el-card v-if="localTestDetail.errorWords?.length" class="error-words-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>错误单词列表</span>
            </div>
          </template>
          <el-table :data="localTestDetail.errorWords" style="width: 100%">
            <el-table-column prop="spelling" label="单词" />
            <el-table-column prop="meaningZhCn" label="中文意思" />
            <el-table-column prop="questionType" label="题目类型">
              <template #default="{ row }">
                <el-tag :type="getQuestionTypeTagType(row.questionType)">
                  {{ getQuestionTypeName(row.questionType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="userAnswer" label="你的答案" />
            <el-table-column prop="correctAnswer" label="正确答案" />
          </el-table>
        </el-card>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useDcyxTestCenterStoreHook } from '@/store'
import type { TestDetailItem } from '@/api/dcyx/test-center.api'

defineOptions({
  name: 'TestDetail',
  inheritAttrs: false,
})

const route = useRoute()
const router = useRouter()
const testCenterStore = useDcyxTestCenterStoreHook()

const loading = ref(false)
const localTestDetail = ref<TestDetailItem>({} as TestDetailItem)

// 获取测试详情
async function fetchTestDetail() {
  const testRecordId = Number(route.params.id)
  if (!testRecordId) {
    ElMessage.error('测试记录ID不存在')
    goBack()
    return
  }

  try {
    loading.value = true
    const detail = await testCenterStore.fetchTestDetail(testRecordId)
    localTestDetail.value = detail
  } catch (error) {
    console.error('获取测试详情失败:', error)
    ElMessage.error('获取测试详情失败')
  } finally {
    loading.value = false
  }
}

// 返回上一页
function goBack() {
  router.back()
}

// 格式化时长
function formatDuration(seconds: number): string {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}分${remainingSeconds}秒`
}

// 获取分数样式类
function getScoreClass(score: number): string {
  if (score >= 90) return 'score-high'
  if (score >= 60) return 'score-medium'
  return 'score-low'
}

// 获取正确率
function getAccuracyRate(): string {
  if (localTestDetail.value.totalQuestions === 0) return '0'
  const rate = (localTestDetail.value.correctAnswers / localTestDetail.value.totalQuestions) * 100
  return rate.toFixed(1)
}

// 获取题目类型名称
function getQuestionTypeName(type: string): string {
  const typeMap: Record<string, string> = {
    memory: '智能记忆',
    dictation: '智能听写',
    writing: '智能默写'
  }
  return typeMap[type] || type
}

// 获取题目类型标签类型
function getQuestionTypeTagType(type: string): string {
  const typeMap: Record<string, string> = {
    memory: 'success',
    dictation: 'warning',
    writing: 'danger'
  }
  return typeMap[type] || 'info'
}

onMounted(() => {
  fetchTestDetail()
})
</script>

<style lang="scss" scoped>
.test-detail {
  padding: 20px;
  height: 100%;
  background-color: var(--el-bg-color-page);

  &__header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;
  }

  &__title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  &__content {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
}

.card-header {
  font-weight: 600;
  font-size: 16px;
}

.test-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;

  .info-item {
    display: flex;
    align-items: center;

    .label {
      font-weight: 500;
      color: var(--el-text-color-secondary);
      min-width: 80px;
    }

    .value {
      color: var(--el-text-color-primary);

      &.score {
        font-weight: 600;
        font-size: 18px;

        &.score-high {
          color: var(--el-color-success);
        }

        &.score-medium {
          color: var(--el-color-warning);
        }

        &.score-low {
          color: var(--el-color-danger);
        }
      }
    }
  }
}

.test-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  text-align: center;

  .stat-item {
    .stat-value {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: 8px;

      &.correct {
        color: var(--el-color-success);
      }

      &.wrong {
        color: var(--el-color-danger);
      }
    }

    .stat-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.error-rate {
  color: var(--el-color-danger);
  font-weight: 500;
}
</style>
